package com.at.bigdata.spark.core.rdd.operator.transform

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

/**
 *
 * @author cdhuangchao3
 * @date 2023/3/19 9:52 PM
 */
object Spark19_RDD_combineByKey {

  def main(args: Array[String]): Unit = {
    // 环境准备
    val sparkConf = new SparkConf()
      .setMaster("local[*]")
      .setAppName("Operator")
    val sc = new SparkContext(sparkConf)

    // 分区内
    // 分区间
    // TODO 算子 - key - value类型
    val rdd1 = sc.makeRDD(List(
      ("a", 1), ("a", 2), ("b", 3),
      ("b", 4), ("b", 5), ("a", 6)
    ), 2)

    // combineByKey
    //        param1 相同的key的第一个数据进行结构的转换
    //        param2 分区内计算规则
    //        param3 分区间计算规则
    val newRDD: RDD[(String, (Int, Int))] = rdd1.combineByKey(
      x => (x, 1),
      (t, v) => {
        (t._1 + v, t._2 + 1)
      },
      (t1, t2) => {
        (t1._1 + t2._1, t1._2 + t2._2)
      }
    )
    newRDD.collect().foreach(println)
    newRDD.map(t => {
      (t._1, t._2._1 / t._2._2)
    }).collect().foreach(println)

  }

}
